package cn.bs.ktv.connection;

import android.util.Log;

import androidx.core.util.Consumer;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.core.utils.SLog;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;

import org.greenrobot.eventbus.EventBus;

import java.util.Objects;

import cn.bs.ktv.model.Constant;
import cn.bs.ktv.model.JsonData;
import cn.bs.ktv.model.PulseData;
import cn.bs.ktv.model.event.MsgEvent;

public class ConnectionMgr {
    private static final String logName = ConnectionMgr.class.getName();
    private static IConnectionManager connectionManager;

    /**
     * 连接
     *
     * @param ip   ip地址
     * @param port 端口
     */
    public static void connect(String ip, int port) {
        connect(ip, port, null);
    }

    /**
     * 连接
     *
     * @param ip   ip地址
     * @param port 端口
     */
    public static void connect(String ip, int port, Consumer<String> consumer) {
        try {
            SLog.setIsDebug(false);
            PulseData pulseData = new PulseData();

            OkSocketOptions.Builder builder = new OkSocketOptions.Builder();
            builder.setMaxReadDataMB(20);
            builder.setPulseFrequency(10000L);
            builder.setReadPackageBytes(4096);
            builder.setReaderProtocol(new KtvReaderProtocol());
            builder.setReader(new KtvSocketReaderImpl());

            connectionManager = OkSocket.open(ip, port).option(builder.build());
            connectionManager.option(builder.build());
            connectionManager.registerReceiver(new SocketActionAdapter() {
                @Override
                public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
                    Log.i(logName, "连接成功," + action);
                    if (!Objects.isNull(consumer)) {
                        consumer.accept(Constant.CONNECTION_SUCCESS);
                    }

                    connectionManager.getPulseManager().setPulseSendable(pulseData).pulse();
                }

                @Override
                public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
                    if (!Objects.isNull(consumer)) {
                        consumer.accept(Constant.CONNECTION_FAIL);
                    }
                }

                @Override
                public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
                    String body = new String(EncodeUtils.base64Decode(data.getBodyBytes()));

                    if (StringUtils.isEmpty(body)) {
                        return;
                    }

//                    Log.i(logName, "the body is:" + body);
                    MsgEvent msgEvent = GsonUtils.fromJson(body, MsgEvent.class);

                    if (Objects.isNull(msgEvent)) {
                        return;
                    }

                    String cmd = msgEvent.getCmd();
                    if (cmd.equals(Constant.CMD.ECHO)) {
                        Log.d(logName, "喂狗成功!");
                        connectionManager.getPulseManager().feed();
                    } else {
                        EventBus.getDefault().post(msgEvent);
                    }
                }
            });

            connectionManager.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否连接成功
     *
     * @return boolean
     */
    public static boolean isConnected() {
        if (Objects.isNull(connectionManager)) {
            return false;
        }

        return connectionManager.isConnect();
    }

    /**
     * 断开连接
     */
    public static void disconnect() {
        if (Objects.isNull(connectionManager)) {
            return;
        }

        connectionManager.disconnect();
    }

    /**
     * 发送数据
     *
     * @param data 数据
     */
    public static void send(ISendable data) {
        if (isConnected()) {
            connectionManager.send(data);
        }
    }

    /**
     * 发送数据
     *
     * @param cmd 命令
     */
    public static void send(String cmd) {
        send(cmd, null);
    }

    /**
     * 发送数据
     *
     * @param cmd  命令
     * @param data 数据
     */
    public static void send(String cmd, Object data) {
        send(new JsonData(cmd, data));
    }
}
